import { LoadingManager, Mesh } from 'three';
import { World } from './World';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader';
import { GLTF, GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { bodyMaterial } from './ModelMaterial';
import { gsap } from 'gsap';

export class ModelLoader {
  private gltfLoader: GLTFLoader;
  private dracoLoader: DRACOLoader;
  private loadingManager: LoadingManager;
  private world: World;
  constructor(World: World) {
    this.loadingManager = new LoadingManager();

    this.gltfLoader = new GLTFLoader(this.loadingManager);

    this.dracoLoader = new DRACOLoader();
    this.dracoLoader.setDecoderPath('draco/gltf/');
    this.dracoLoader.preload();
    this.gltfLoader.setDRACOLoader(this.dracoLoader);
    this.world = World;

    this.loadingManager.onLoad = () => {
      // const preloaderBg = <HTMLDivElement>document.getElementsByClassName('preloader-bg')[0];
      // const clouds = <HTMLDivElement>document.getElementsByClassName('preloader-clouds')[0];
      // if (!preloaderBg.classList.contains('none')) {
      //   gsap.to(this.world.camera.position, { z: 50, direction: 1, delay: 1, duration: 2 });
      // }
      // preloaderBg.classList.add('none');
      // clouds.classList.add('move');
    };
  }

  public loadModelToScene(url: string) {
    this.gltfLoader.load(
      url,
      (gltf: GLTF) => {
        const model = gltf.scene;
        // var boundingBox = new Box3().setFromObject(model);

        // 计算模型在Y轴上的高度
        // var height = boundingBox.max.y - boundingBox.min.y;

        // // 缩放模型以在Y轴上进行压扁
        // model.scale.y = 0.05; // 或根据需要调整压扁的程度
        // gsap.to(model.scale, { y: 0.05, direction: 1, delay: 1, duration: 10 });
        model.traverse((child) => {
          const $child = child as Mesh;

          if ($child.name.includes('metal')) {
            $child.material = bodyMaterial;
            // $child.material.transparent = true; // 设置材质为半透明
            // $child.material.opacity = 0.5; // 设置透明度
          } else if ($child.name.includes('site')) {
            // $child.visible = true;
          }
        });
        this.world.add(model);
      },
      (xhr) => {
        // const preloaderLoader = <HTMLDivElement>document.getElementsByClassName('preloader-bar--loader')[0];
        // preloaderLoader.style.width = Math.floor((xhr.loaded / xhr.total) * 90) + '%';
      }
    );
  }
  public addModel(url: string, callback: () => void) {
    this.gltfLoader.load(url, (gltf: GLTF) => {
      const model = gltf.scene;

      model.traverse((child) => {
        const $child = child as Mesh;
        if ($child.name.includes('metal')) {
          $child.material = bodyMaterial;
        } else if ($child.name.includes('site')) {
        }
      });
      this.world.camera.position.set(0, 50, 50);
      this.world.add(model);
      if (callback) {
        callback();
      }
    });
  }
}
